import { getCurrentUserInfo } from '@/apis/accessManagement/user'
import { WebSee } from '@/utils/webSee'
import { makeAutoObservable } from 'mobx'
import { storage } from '@/utils/Storage'

class GlobalUser {
  token: string | null = storage.get('TOKEN')
  userInfo: Partial<User.UserEntity> = {}
  menuInfo = []
  userAuths: Array<number> = []
  constructor() {
    makeAutoObservable(this)
  }

  async getUserDetail(userId: string) {
    const res = await getCurrentUserInfo(userId)
    res?.data?.userID !== 'imAdmin' && storage.set('roleId', res?.data?.roleId)
    this.userInfo = res?.data
    new WebSee(res?.data?.nickname)
  }

  setUserInfo(user: Partial<User.UserEntity>) {
    this.userInfo = user
  }
  setMenuInfo(list: any) {
    this.menuInfo = list
  }
  setUserAuths(list: Array<number>) {
    this.userAuths = list
  }
  setToken(newToken: string | null) {
    this.token = newToken
    if (newToken) {
      storage.set('TOKEN', newToken) // 更新到 localStorage
    } else {
      storage.remove('TOKEN') // 清除 token
    }
  }
  get authMenuPaths() {
    const obj: Record<string, boolean> = {}
    if (this.userInfo?.userID === 'imAdmin') {
      // 如果用户为 admin，则所有菜单的 path 都设置为 true
      this.menuInfo.forEach((menu: any) => {
        obj[menu.path] = true
      })
    } else {
      // 根据 userAuths 和 menuInfo 计算
      this.menuInfo.forEach((menu: any) => {
        if (this.userAuths.includes(menu.menuId)) {
          obj[menu.path] = true
        }
      })
    }
    return obj
  }
}

export const storeGlobalUser = new GlobalUser()
